import router from './router'
import store from './store'
import { Message } from 'element-ui'

// 白名单路由
const whiteList = ['/index', '/help', '/login']

router.beforeEach(async (to, from, next) => {
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - ${process.env.VUE_APP_TITLE}` : process.env.VUE_APP_TITLE

  // 获取token
  const hasToken = store.state.auth.token || JSON.parse(localStorage.getItem('token'))

  if (hasToken) {
    if (to.path === '/login') {
      next({ path: '/home' })
    } else {
      const hasRoutes = store.state.auth.routes?.length > 0
      if (hasRoutes) {
        next()
      } else {
        try {
          // 重新加载路由
          const accessRoutes = await store.dispatch('auth/reloadRoutes')
          if (accessRoutes.length > 0) {
            next({ ...to, replace: true })
          } else {
            await store.dispatch('auth/logout')
            next('/index')
          }
        } catch (error) {
          console.error('Error loading routes:', error)
          await store.dispatch('auth/logout')
          next('/index')
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next('/index')
    }
  }
})

router.afterEach(() => {
  // 路由切换后的操作
})
